package conchmusic.conchmusicclient.util;

import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;

import conchmusic.conchmusicclient.dao.ClientControl;
import conchmusic.conchmusicclient.dao.MyDBHelp;
import conchmusic.conchmusicclient.pojo.Progressor;
import conchmusic.conchmusicclient.pojo.Song;
import conchmusic.conchmusicclient.thread.play_OnlineThread;

/**
 * Created by sbml1 on 2017/4/7.
 */

public class MusicService2 extends Service {
    private MediaPlayer player;
    private String action;
    private int posit;
    private String[] list;
    private boolean isPause;
    private int progress;
    private boolean isExit=false;
    private int localSongId=0;
    //private Song song;
    private boolean playing=false;
    private int duration=0;
    private MyDBHelp dbHelp=new MyDBHelp(this,"demon",null,1);
    private ClientControl clientControl=new ClientControl(dbHelp);
    private Intent intentRece;
    private Song song0;
    private boolean hasPrepared=false;
    @Override
    public void onCreate() {
        super.onCreate();
        Thread.setDefaultUncaughtExceptionHandler(Thread.getDefaultUncaughtExceptionHandler());

        player=new MediaPlayer();

        //自动播放下一首
        player.setOnCompletionListener(new CompletionListener());
        player.setOnPreparedListener(new PreparedListener());

        intentRece=new Intent("conchumusic.conchumusicclient.RECEIVER");
        //开启广播
        new Thread(new Runnable() {
            @Override
            public void run() {

                while(!isExit){
                    songInfo();
                    playing=player.isPlaying();
                    if(playing){
                        progress=player.getCurrentPosition();
                    }
                    intentRece.putExtra("duration",duration);
                    intentRece.putExtra("progress",progress);
                    intentRece.putExtra("songList",list);
                    intentRece.putExtra("playing",playing);
                    sendBroadcast(intentRece);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

    }



    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        action=intent.getStringExtra("action");
        int posit0=intent.getIntExtra("posit",posit);
        if(posit0>=0){
            posit=posit0;
        }
        list=intent.getStringArrayExtra("songList");
        Log.i("service posit",posit+"...");


        switch (action){
            case "playDirect":
                playDirect(posit);
                break;
            case "play":
                play(posit);
                break;
            case "pause":
                pause(posit);
                break;
            case "next":
                if(posit>=list.length-1){
                    posit=0;
                }else{
                    posit=posit+1;
                }
                playDirect(posit);
                break;
            case "previous":
                if(posit==0){
                    posit=list.length-1;
                }else {
                    posit=posit-1;
                }
                playDirect(posit);
                break;
            case "jump":
                progress=intent.getIntExtra("jump",progress);
                jump(progress);
                break;

        }

        return super.onStartCommand(intent, flags, startId);
    }

    public void jump(int jump){
        player.seekTo(jump);
    }


    public void pause(int posit){
        player.pause();
        isPause=true;
//        playing=false;
    }

    //不论是否暂停状态，直接开始播放
    public void playDirect(int posit){
        if(hasPrepared){
            player.reset();
        }
        String Url="";
        try {
            song0=getSongByPosit(posit);
            if(song0!=null){
                Url=song0.getLocalSongUrl();
                if(Url==null){
                    Url=song0.getSongUrl();
                }
            }
            //Url="http://m2.music.126.net/0Dtxce8suKm0-AvgDEIPtQ==/5847202836671588.mp3";
            Log.i("DUrl in service","..."+Url);
            player.setDataSource(Url);
            player.prepareAsync();
            //player.start();
        } catch (Exception e) {
            e.printStackTrace();
            Log.i("MusicService150","error");
        }
        isPause=false;
//        playing=true;
    }

    //改变播放、暂停状态
    public void play(int posit){
        if(!isPause){
            player.reset();
            try {
                song0=getSongByPosit(posit);
                String Url="";
                if(song0!=null){
                    Url=song0.getLocalSongUrl();
                    if(Url==null){
                        Url=song0.getSongUrl();
                    }
                }
                //Url="http://m2.music.126.net/0Dtxce8suKm0-AvgDEIPtQ==/5847202836671588.mp3";
                Log.i("PUrl in service","..."+Url);
                player.setDataSource(Url);
                player.prepareAsync();
            } catch (Exception e) {
                e.printStackTrace();
                Log.i("MusicService175","error");
            }
        }else{
            player.start();
        }
        isPause=false;
//        playing=true;
    }

    //根据列表list和位置posit获取当前歌曲song
    private Song getSongByPosit(int posit){
        Song song;
        if(list==null){
            return null;
        }
        int localId= Integer.parseInt(list[posit]);
        song=clientControl.findSong(localId);
        if(song==null){
            return null;
        }
//        if(song.getLocalSongUrl()==null || song.getLocalSongUrl().length()==0){
//            play_OnlineThread playOnlineThread =new play_OnlineThread(song,this);
//            new Thread(playOnlineThread).start();
//        }
        return song;
    }


    @Override
    public IBinder onBind(Intent intent) {
        return new Progressor(player);
    }

    public void songInfo(){
        //歌曲相关信息
        intentRece.putExtra("localSongId",localSongId);
        Song song=getSongByPosit(posit);
        if(song!=null) {
            localSongId = song.getLocalSongId();
            intentRece.putExtra("title", song.getTitle());
            intentRece.putExtra("localPictureUrl", song.getLocalPictureUrl());
        }

    }


    //播放完成
    private final class CompletionListener implements MediaPlayer.OnCompletionListener {

        @Override
        public void onCompletion(MediaPlayer mp) {
            if(posit>=list.length-1){
                posit=0;
            }else{
                posit=posit+1;
            }
            playDirect(posit);
        }

    }

    private final class PreparedListener implements MediaPlayer.OnPreparedListener{

        @Override
        public void onPrepared(MediaPlayer mp) {
            mp.start();
            duration=mp.getDuration();
            hasPrepared=true;
        }
    }

    public class Other extends Activity implements Thread.UncaughtExceptionHandler {

        //必须实现接口uncaughtException
        @Override
        public void uncaughtException(Thread arg0, Throwable arg1) {
            //在此处理异常， arg1即为捕获到的异常
            Log.i("AAA", "uncaughtException   " + arg1);
        }

    }

    @Override
    public void onDestroy() {
        isExit=true;
        super.onDestroy();
    }
}
